package com.zjhcsoft.auth.controller;

import com.dc.eai.data.CompositeData;
import com.dcfs.esb.utils.TLSimRepTools;
import com.zjhcsoft.auth.common.enums.ApiCode;
import com.zjhcsoft.auth.common.utils.ResultUtil;
import com.zjhcsoft.auth.common.vo.Result;
import com.zjhcsoft.auth.entity.Account;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.IOException;

import static com.zjhcsoft.auth.common.constant.RedisKeyConstant.TOKEN_PREFIX;

/**
 * 登出
 * @author wzya
 * @date 2021/03/21
 */
@RestController
@RequestMapping("/logout")
public class LogoutController {

    @Resource
    private RedisTemplate<String, Account> redisTemplate;
    /**
     * 用户退出

     */
    @PostMapping
    @ApiOperation(value="用户退出")
    public String exit(HttpServletRequest request, HttpServletResponse response){

        String resultMsg = "";
        Result result = new Result();
        try{
            BufferedInputStream is = new BufferedInputStream(request.getInputStream());
            CompositeData reqCD = TLSimRepTools.xmlToCD(IOUtils.toByteArray(is), "UTF-8");
            CompositeData sys = reqCD.getStruct("SYS_HEAD");
            CompositeData app = reqCD.getStruct("APP_HEAD");
            //报文解析
            String token = (String) ResultUtil.xmlToApiRequest(reqCD);

            if(redisTemplate.hasKey(TOKEN_PREFIX+":"+token)){
                if(redisTemplate.delete(TOKEN_PREFIX+":"+token)){
                    result =  Result.ok("exit success.");
                }else {
                    result =  Result.error("exit failed.");
                }
            }else{
                result = Result.error("invalid token.");
            }
            result.setType(ApiCode.EXIT.getName());
            //返回报文组装
            resultMsg = ResultUtil.getBodyForAuth(null,sys,app,result);
        }catch (IOException e) {
            e.printStackTrace();
        }
        return resultMsg;


    }

}
